package com.copa.l77;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author copa
 * @createDate 2022-05-16 17:27
 * @function 回溯法 我终于第一次做出非暴力法解决的啦...心里有点小激动O(∩_∩)O
 */
public class Test1 {

    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        // 首先我这里是用了标记法，遍历过的就不再遍历，防止重复
        HashMap<Integer, Boolean> visited = new HashMap();
        for (int i = 1; i <= n; i++) {
            visited.put(i, false);
        }
        backTracking(n, k, result, new ArrayList<Integer>(), visited);
        return result;
    }

    private void backTracking(int n, int k, List<List<Integer>> result, ArrayList<Integer> tempList, HashMap<Integer, Boolean> visited) {
        if (k == tempList.size()) {
            result.add(new ArrayList<>(tempList));
            return;
        }
        for (int i = 1; i <= n; i++) {
            Boolean flag = visited.get(i);
            // 这里添加一个条件就是为了预防后面一个数比前面一个数大的情况...虽然看起来蛮繁琐的o(╥﹏╥)o
            if (!flag && (tempList.size() < 1
                    || (tempList.size() >= 1 && tempList.get(tempList.size() - 1) < i))) {
                visited.put(i, true);
                tempList.add(i);
                backTracking(n, k, result, tempList, visited);
                visited.put(i, false);
                tempList.remove(tempList.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> combine = new Test1().combine(4, 2);
        for (List<Integer> list : combine) {
            System.out.println(Arrays.toString(list.toArray()));
        }
    }
}
